package com.sh.weblogspringboot.jwt.handler;

import com.sh.weblogspringboot.common.enums.ResponseCodeEnum;
import com.sh.weblogspringboot.common.util.Response;
import com.sh.weblogspringboot.jwt.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author songHai
 * @Classname RestAuthenticationEntryPoint
 * @Description 处理器，它专门用来处理当用户未登录时，访问受保护的资源的情况：
 * @Date 2025/3/27 1:06
 */
@Component
@Slf4j
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.warn("用户未登录访问受保护的资源：", authException);
        // 当请求相关受保护的接口时，请求头中未携带 Token 令牌，通过日志打印异常信息
        if (authException instanceof InsufficientAuthenticationException) {
            ResultUtil.fail(response, HttpStatus.UNAUTHORIZED.value(), Response.fail(ResponseCodeEnum.UNAUTHORIZED));
        }

        ResultUtil.fail(response, HttpStatus.UNAUTHORIZED.value(), Response.fail(authException.getMessage()));
    }
}
